
let db = {};
const Sequelize = require('sequelize');
const sequelize = new Sequelize('logger', 'postgres', '1', {
    host: '127.0.0.1',
    dialect: 'postgres',
    logging: false,

    // 设置时区
    timezone: '+08:00',

    pool: {
        max: 50,
        min: 0,
        acquire: 30000,
        idle: 10000
    }
}
);

sequelize
    .authenticate()
    .then(() => {
        console.log('连接数据库，成功');
        Pressure.sync()
            .then(() => {
                console.log("同步表格 Pressure");
            });
	Logger.sync()
	   .then(() => {
	       console.log("同步表格 Logger");	
	   });

    })
    .catch(err => {
        console.error(err.toString());
    });

// 记录
class Logger extends Sequelize.Model { }
Logger.init({
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    number: { type: Sequelize.INTEGER },
    ts: { type: Sequelize.DATE },
    created: { type: Sequelize.DATE },
    type: { type: Sequelize.STRING },
    factory: { type: Sequelize.INTEGER }
},
    {
        sequelize,
        modelName: 'myData',
        timestamps: false
    });


// 压力记录
class Pressure extends Sequelize.Model { }
Pressure.init({
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    number: { type: Sequelize.DOUBLE },
    ts: { type: Sequelize.DATE },
    type: { type: Sequelize.STRING },  // 1线， 2线， 2工厂
},
    {
        sequelize,
        modelName: 'pressureData',
        timestamps: false
    });


// 插入记录：数量，世界，类型，工厂
db.add_record = function (nm, ts, tp, fc) {
    //console.log(`db: 数量：${nm}，时间：${ts}，类型：${tp}，工厂：${fc}`);
    Logger.create({
        number: nm,
        ts: ts,
        type: tp,
        factory: fc
    });
};


db.add_record_pressure = function (nm, ts, tp) {
    //console.log(`db: 数量：${nm}，时间：${ts}，类型：${tp}`);
    Pressure.create({
        number: nm,
        ts: ts,
        type: tp
    });
};


db.Logger = Logger;
db.Pressure = Pressure;
db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
